﻿using MQTTnet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZPLPrinterProject;
using AntdUI;
using Flurl;
using Flurl.Http;
using static AntdUI.Table;

namespace CSharpTest
{
    public partial class Form1 : Form
    {
        public string m_zpl_content {  get; set; }
        public MQTClientHelper client = new MQTClientHelper();

        public FlurlApiService m_flurl = new FlurlApiService();

        public Form1()
        {
            InitializeComponent();
            //_ = InitMQTTClient();

            //FlurlTest();

            //JsonToIni();
            IniToJson();
        }

        #region JsonAndIni
        public void JsonToIni()
        {
            string jsonContent = File.ReadAllText("config.json");
            CovertJsonIni.ConvertJsonToIni(jsonContent, "config.ini");
        }

        public void IniToJson()
        {
            string iniPath = "config.ini";
            string jsonResult = CovertJsonIni.ConvertIniToJson(iniPath);
            File.WriteAllText("config.json", jsonResult);
        }

        #endregion

        #region Flurl使用

        public async void FlurlTest()
        {
            var param = new Login()
            {
                Name = "test",
                Pwd = "test2",
            };
            //var response = await m_flurl.GetStringAsync("127.0.0.1", 8080, "/api/login", param);
            //ShowLog(response.Success? response.ResponseContent : response.ErrMessage);


            var param2 = new Login2()
            {
                Name = "test",
                Pwd = "test2",
                Pwd2 = "test3",
            };
            //var response = await m_flurl.GetJsonAsync<Login2>("127.0.0.1", 8080, "/api/login", param2);
            //Login ret = response.Obj as Login;
            //ShowLog(response.Success ? $"{ret.Name} : {ret.Pwd}" : response.Message);

            //var response3 = await m_flurl.PostJsonAsync<Login>("127.0.0.1", 8080, "/api/login", param);
            var response4 = await m_flurl.PostJsonToStringAsync("127.0.0.1", 8080, "/api/login", param);

        }

        #endregion

        #region MQTT测试
        private Task InitMQTTClient()
        {
            // 注册消息接收事件
            client.MessageReceived += (sender, e) =>
            {
                var payload = e.ApplicationMessage.ConvertPayloadToString();
                ShowLog($"客户端收到消息 - 主题: {e.ApplicationMessage.Topic}, 内容: {payload}");
            };
            // 连接设置
            string serverIp = "127.0.0.1";
            int serverPort = 8080;
            // 创建并连接客户端
            ShowLog($"连接到服务器 {serverIp}:{serverPort}...");
            client.Start(serverIp, serverPort);
            // 简单等待连接完成
            Thread.Sleep(2000);
            // 订阅测试主题
            string subscribeTopic = "test/topic";
            client.SubscribeAsync(subscribeTopic);
            ShowLog($"已订阅主题: {subscribeTopic}");

            return Task.CompletedTask;
        }
        public void SendMsgMQ(string msg)
        {
            // 发布测试消息
            string publishTopic = "test/topic2";
            client.PublishMesage(publishTopic, msg);
            ShowLog($"已发布消息到 {publishTopic}: {msg}");
        }
        private void button_MQTTDisconnect_Click(object sender, EventArgs e)
        {
            client.Client_Disconect(); // 断开连接
            ShowLog("MQTT已断开连接");
        }
        
        private void button_send_Click(object sender, EventArgs e)
        {
            string msg = input_MQMsg.Text;
            SendMsgMQ(msg);
        }
        #endregion

        #region 打印机
        /// <summary>
        /// 打印机
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_print_Click(object sender, EventArgs e)
        {
            string path = Environment.CurrentDirectory + @"\Config\TagPrint.txt";
            if (File.Exists(path))
            {
                m_zpl_content = File.ReadAllText(path);
            }
            else
            {
                return;
            }
            PrintDialog printDialog = new PrintDialog();
            printDialog.PrinterSettings = new PrinterSettings();
            if (DialogResult.OK != printDialog.ShowDialog(this))
                return;

            string zpl_content = m_zpl_content;
            RawPrinterHelper.SendStringToPrinter(printDialog.PrinterSettings.PrinterName, zpl_content);
            MessageBox.Show("打印完成");
        }
        #endregion

        private void ShowLog(string msg)
        {
            string date = DateTime.Now.ToString();

            string text = $"[{date}]{msg}\n";

            if (richTextBox_log.InvokeRequired)
            {
                // 跨线程时通过委托调用自身
                richTextBox_log.Invoke(new Action(() =>
                {
                    richTextBox_log.AppendText(text);
                }));
            }
            else
            {
                // 当前已是 UI 线程，直接操作
                richTextBox_log.AppendText(text);
            }
        }

    }
}
